package com.feicheng.iou.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feicheng.iou.constant.SessionConstant;
import com.feicheng.iou.entity.Resource;
import com.feicheng.iou.mapper.ResourceMapper;
import com.feicheng.iou.pojo.*;
import com.feicheng.iou.pojo.excelHandle.ExcelOutModel;
import com.feicheng.iou.pojo.lifeCyclePOJO.*;
import com.feicheng.iou.pojo.login.LoginReturnPOJO;
import com.feicheng.iou.pojo.login.PermissionLevelTwoPOJO;
import com.feicheng.iou.pojo.login.PermissionListPOJO;
import com.feicheng.iou.pojo.resourcePublicSeaPOJO.ResourcePublicSeaParamPOJO;
import com.feicheng.iou.pojo.resourcePublicSeaPOJO.ResourcePublicSeaReturnListPOJO;
import com.feicheng.iou.pojo.resourcePublicSeaPOJO.ResourcePublicSeaReturnPOJO;
import com.feicheng.iou.result.ResultInfo;
import com.feicheng.iou.commom.ReturnCode;
import com.feicheng.iou.constant.StatuConstant;
import com.feicheng.iou.entity.*;
import com.feicheng.iou.exception.SystemException;
import com.feicheng.iou.mapper.*;
import com.feicheng.iou.service.ExcelOutMapperService;
import com.feicheng.iou.service.ResourceService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.feicheng.iou.util.PageUtil;
import org.springframework.core.io.ResourceEditor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.net.TelnetInputStream;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.net.URLEncoder;

import java.util.List;

import javax.lang.model.element.VariableElement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianchunlei
 * @since 2021-06-28
 */
@Service
@Slf4j
@Setter
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper; //线索映射

    @Autowired
    private ResourcePublicSeaReturnPOJO resourcePublicSeaReturnPOJO; //公海管理返回信息

    @Autowired
    private PersonalDetailPOJO personalDetailPOJO;  //个人信息返回信息

    @Autowired
    private ResourceAndBackviewPOJO resourceAndBackviewPOJO; //封装线索和其回访

    @Autowired
    private InterviewAndBackviewPOJO interviewAndBackviewPOJO;  //封装接待和其回访

    @Autowired
    private TryAndBackviewPOJO tryAndBackviewPOJO;  //封装试听和其回访

    @Autowired
    private BaomingAndBackviewPOJO baomingAndBackviewPOJO;//封装报名及其回访

    @Autowired
    private LifeCyclePOJO lifeCyclePOJO; //封装声明周期信息

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ResourceRecordMapper resourceRecordMapper;

    @Autowired
    private ReservationBackviewMapper reservationBackviewMapper;

    @Autowired
    private ReservationInterviewMapper reservationInterviewMapper;

    @Autowired
    private ReservationTryMapper reservationTryMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BaomingMapper baomingMapper;

    @Autowired
    private BackviewMapper backviewMapper;

    @Autowired
    ExcelOutMapperService excelService;

    @Autowired
    TryMapper tryMapper;

    @Autowired
    InterviewMapper interviewMapper;


    @Autowired
    private HttpSession session;


    /**
     * @param name 学生姓名
     * @return ResultInfo
     * @Author xuxinjie
     * @Description 根据学生name 查重学生信息接口
     * @Date 2021-7-3 16:08
     */
    @Override
    @Transactional
    public ResultInfo selectResourceByName(String name) {

        log.info("ResourceServiceImpl 的selectResourceByName方法进入");

        //绑定mybatis-plus学生查询条件
        QueryWrapper<Student> wrapperStudentName = new QueryWrapper<>();
        wrapperStudentName.like("name", name);
        QueryWrapper<Student> wrapperStudentTel = new QueryWrapper<>();
        wrapperStudentTel.like("tel",name);

        List<Student> studentList = new ArrayList<>();
        //将查询到的结果存入studentList中，且只返回"id","name","tel"三列
        List<Student> studentListByTel = studentMapper.selectList(wrapperStudentTel.select("id", "name", "tel"));
        //将查询到的结果存入studentList中，且只返回"id","name","tel"三列
        List<Student> studentListByName = studentMapper.selectList(wrapperStudentName.select("id", "name", "tel"));
        //遍历studentListByTel，每一个对象都插入studentList
        for (Student student:studentListByTel){
            studentList.add(student);
        }
        //遍历studentListByName，每一个对象都插入studentList
        for(Student student:studentListByName){
            studentList.add(student);
        }
        //把list放入HashSet保证数据不会重复
        HashSet hashSet = new HashSet(studentList);
        /* 清空集合，把hashset中数据重新放入list */
        studentList.clear();
        studentList.addAll(hashSet);


        //绑定mybatis-plus线索查询条件
        QueryWrapper<Resource> wrapperResource = new QueryWrapper<>();
        wrapperResource.inSql("student_id", "select id from student where name like '%" + name + "%' or tel like '%" + name + "%'");


        //将查询到的结果封装resources中，且只返回"id","statu","autor"三列
        List<Resource> resources = resourceMapper.selectList(wrapperResource.select("id", "statu", "autor", "student_id"));

        //定义List封装ResourceDuplicatePOJO对象
        List<ResourceDuplicatePOJO> resourceDuplicatePOJOList = new ArrayList<>();
        //循环将resourceDuplicatePOJO中的参数传入List中
        for (int i = 0; i < studentList.size(); i++) {
            ResourceDuplicatePOJO resourceDuplicatePOJO = new ResourceDuplicatePOJO();
            resourceDuplicatePOJO.setStudent(studentList.get(i));
            resourceDuplicatePOJO.setResource(resources.get(i));
            resourceDuplicatePOJOList.add(resourceDuplicatePOJO);
        }

        log.info("ResourceServiceImpl 的selectResourceByName结束");
        return ResultInfo.success(resourceDuplicatePOJOList);
    }

    @Override
    public void excelOut(HttpServletResponse response) throws IOException {
        log.info("ResourceServiceImpl的 downloadFailedUsingJson方法进入");
        List<ExcelOutModel> excelModels = (List<ExcelOutModel>) session.getAttribute("excelModels");

        ExcelWriter excelWriter = null;

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("线索", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            excelWriter = EasyExcel.write(response.getOutputStream(), ExcelOutModel.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
            excelWriter.write(excelModels, writeSheet);
            //.autoCloseStream(Boolean.FALSE).sheet("模板")
            //.doWrite(excelModels);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("STATUS", "EXCEL_PARSE_ERROR");
            map.put("MESSAGE", "下载文件失败");
            response.getWriter().println(JSON.toJSONString(map));
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }

        log.info("ResourceServiceImpl的 downloadFailedUsingJson方法结束");

    }
    /**
     * @Author luoxin
     * @Description 公海转线索
     * @Date 1:22 下午 2021/8/5
     * @param null
     * @return
     */
    @Override
    public ResultInfo transferRessource(ResourcePOJO resourcePOJO) {
        log.info("ResourceServiceImpl的 transferRessource方法进入");
        //解析POJO封装到entity
        Student student = resourcePOJO.getStudent();//解析Resource
        Resource resource = resourcePOJO.getResource();//解析Student
        ResourceRecord resourceRecord = resourcePOJO.getResourceRecord();//解析ResourceRecord

        //获取学生Id
        Integer studentId = student.getId();
        //获取线索Id
        Integer resourceId = resource.getId();
        //封装学生Id
        QueryWrapper studentQueryWrapper = new QueryWrapper();
        studentQueryWrapper.eq("student_id",studentId);
        //封装线索Id
        QueryWrapper resourceQueryWrapper = new QueryWrapper();
        resourceQueryWrapper.eq("resource_id",resourceId);
        //根据学生id删除ressource
        resourceMapper.delete(studentQueryWrapper);
        //根据线索id删除resourceRecord
        resourceRecordMapper.delete(resourceQueryWrapper);
        //根据学生id删除reservationInterview
        reservationInterviewMapper.delete(studentQueryWrapper);
        //根据学生id删除reservationBackview
        reservationBackviewMapper.delete(studentQueryWrapper);
        //根据学生id删除reservationTry
        reservationTryMapper.delete(studentQueryWrapper);
        //根据学生id删除interview
        interviewMapper.delete(studentQueryWrapper);
        //根据学生id删除try
        tryMapper.delete(studentQueryWrapper);
        //根据学生id删除baoming
        baomingMapper.delete(studentQueryWrapper);
        //根据学生id删除backview
        backviewMapper.delete(studentQueryWrapper);
        //根据学生id删除student
        studentMapper.deleteById(studentId);

        //重新封装数据，使所有Id都为空
        student.setId(null);
        resource.setId(null);
        resourceRecord.setId(null);
        ReservationBackview reservationBackview = new ReservationBackview();//解析ReservationBackview
        ReservationInterview reservationInterview = new ReservationInterview();//解析ReservationInterview

        //处理student添加，调用mapper
        int insertStudentResult = studentMapper.insert(student);
        //验证是否成功插入student
        if (insertStudentResult == 0) {
            throw new SystemException(ReturnCode.STUDENT_INSERT_FAIL);
        }

        //取到插入的studentID
        Integer studentNewId = student.getId();
        //将取到studentID插入resource
        resource.setStudentId(studentNewId);
        resource.setStatu(StatuConstant.XIANSUODAIHUIFANG);
        //处理resource添加，调用mapper
        int insertResourceResult = resourceMapper.insert(resource);
        //验证是否成功插入resource
        if (insertResourceResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_INSERT_FAIL);
        }

        //取到插入的resourceID
        Integer resourceNewId = resource.getId();
        //将取到的resourceID插入resouceRecord
        resourceRecord.setResourceId(resourceNewId);
        //处理resourceRecord添加，调用mapper
        int insertResouceRecordResult = resourceRecordMapper.insert(resourceRecord);
        //验证是否成功插入resourceRecord
        if (insertResouceRecordResult == 0) {
            throw new SystemException(ReturnCode.RESOURCERECORD_INSERT_FAIL);
        }

        //取到插入线索的stageId
        reservationBackview.setStageId(1);
        //取到插入的studentID
        reservationBackview.setStudentId(student.getId());
        //处理reservationBackview添加，调用mapper
        int insertReservationBackview = reservationBackviewMapper.insert(reservationBackview);
        //验证是否成功插入resourceRecord
        if (insertReservationBackview == 0) {
            throw new SystemException(ReturnCode.INSERT_RESERVATION_BACKVIEW_FAIL);
        }

        //取到插入的studentID
        reservationInterview.setStudentId(student.getId());
        //处理reservationInterview添加，调用mapper
        int insertReservationInterview = reservationInterviewMapper.insert(reservationInterview);
        //验证是否成功插入resourceRecord
        if (insertReservationInterview == 0) {
            throw new SystemException(ReturnCode.INSERT_RESERVATION_BACKVIEW_FAIL);
        }

        log.info("ResourceServiceImpl的 transferRessource方法进入");
        return ResultInfo.success();
    }


    /**
     * @param studentId 学生Id
     * @return void
     * @Author wuweinan
     * @Description 根据学生id查看学生线索详情
     * 下面还有一个根据studentId查询Resource的方法,但这个是个人详情信息接口用的方法.下面用的是声明周期方法.
     * @Date 2021-6-29 17:38
     */
    @Override
    @Transactional
    public Resource selectResourceByStudentIdPersonalDetail(Integer studentId) {
        log.info("ResourceServiceImpl的selectResourceByStudentIdPersonalDetail进入");

        //根据学生Id查询线索
        QueryWrapper<Resource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        Resource resource = resourceMapper.selectOne(queryWrapper);

        //封装信息
        personalDetailPOJO.setResource(resource);
        log.info("ResourceServiceImpl的selectResourceByStudentIdPersonalDetail返回");
        return resource;

    }


    /**
     * @param studentId 学生Id
     * @return Resource
     * @Author wuweinan
     * @Description 根据学生id查看学生线索详情
     * 声明周期方法.
     * @Date 2021-6-29 17:38
     */
    @Override
    public ResultInfo selectResourceByStudentIdLifeCycle(Integer studentId) {
        log.info("ResourceServiceImpl的selectResourceByStudentIdLifeCycle进入");

        String StageName = "";

        //根据学生Id查询线索
        QueryWrapper<Resource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        Resource resource = resourceMapper.selectOne(queryWrapper);

        //封装信息
        resourceAndBackviewPOJO.setResource(resource);


        //封装信息
        lifeCyclePOJO.setInterviewAndBackviewPOJO(interviewAndBackviewPOJO);
        lifeCyclePOJO.setResourceAndBackviewPOJO(resourceAndBackviewPOJO);
        lifeCyclePOJO.setTryAndBackviewPOJO(tryAndBackviewPOJO);
        lifeCyclePOJO.setBaomingAndBackviewPOJO(baomingAndBackviewPOJO);


        //将所有的生命周期信息封装
        List<Object> objectList = new ArrayList<>();
        objectList.add(interviewAndBackviewPOJO.getInterview());
        objectList.add(resourceAndBackviewPOJO.getResource());
        objectList.add(tryAndBackviewPOJO.getTry());
        objectList.add(baomingAndBackviewPOJO.getBaoming());

        //--------------------------------------------------------------------------
        Set<String> dateSet = new HashSet<>();
        //在这里做时间轴!!!
        //第一步 把所有的时间全部取出来做成一个去重Set
        //若对应学生的线索不为空,则获取到resource的插入时间
        if(resourceAndBackviewPOJO.getResource() != null){
            dateSet.add(resourceAndBackviewPOJO.getResource().getCt().toString().substring(0, 10));
        }

        //若线索阶段进行了回访,则获取到resource阶段的backview的dateTime
        if(resourceAndBackviewPOJO.getBackviewList() != null){

            for (Backview backview : resourceAndBackviewPOJO.getBackviewList()) {
                dateSet.add(backview.getDateTime().toString().substring(0, 10));
                objectList.add(backview);
            }
        }


        //若对应学生到访了,则获取到interview的dateTime
        if(interviewAndBackviewPOJO.getInterview() != null){
            dateSet.add(interviewAndBackviewPOJO.getInterview().getDateTime().toString().substring(0, 10));
        }


        //若对到访阶段做了回访,则获取到interview阶段的backview阶段的dateTime
        if(interviewAndBackviewPOJO.getBackviewList() != null){
            for (Backview backview : interviewAndBackviewPOJO.getBackviewList()) {
                dateSet.add(backview.getDateTime().toString().substring(0, 10));
                objectList.add(backview);
            }
        }


        //如果进行了试听,则获取到try的dateTime
        if(tryAndBackviewPOJO.getTry() != null){
            dateSet.add(tryAndBackviewPOJO.getTry().getDateTime().toString().substring(0, 10));
        }


        //如果对试听阶段做了回访,则获取到try阶段的backview阶段的dateTime
        if(tryAndBackviewPOJO.getBackviewList() != null){
            for (Backview backview : tryAndBackviewPOJO.getBackviewList()) {
                dateSet.add(backview.getDateTime().toString().substring(0, 10));
                objectList.add(backview);
            }
        }



        //如果进行了报名,则获取到try的dateTime
        if(baomingAndBackviewPOJO.getBaoming() != null){
            dateSet.add(baomingAndBackviewPOJO.getBaoming().getDateTime().toString().substring(0, 10));
        }


        //如果对报名阶段做了回访,则获取到报名阶段的backview阶段的dateTime
        if(baomingAndBackviewPOJO.getBackviewList() != null){
            for (Backview backview : baomingAndBackviewPOJO.getBackviewList()) {
                dateSet.add(backview.getDateTime().toString().substring(0, 10));
                objectList.add(backview);
            }
        }


        //将所有的的日期做去重
        List<Date> dateListDate = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (String s : dateSet) {
            try {
                dateListDate.add(simpleDateFormat.parse(s));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        //排序
        dateListDate.sort((t1, t2) -> t1.compareTo(t2));

        //去重 排序 之后的日期<String>
        List<String> dateListString = new ArrayList<>();

        for (Date date : dateListDate) {
            dateListString.add(simpleDateFormat.format(date));
        }

        //封装信息
        List<LifeCycleTimeLinePOJO> lifeCycleTimeLinePOJOList = new ArrayList<>();
        /*
         * 接下来的是...算了 我举个列子吧.上图.这里对应那天的还没排序. resource.生命周期举例子.png
         *
         */
        for (String date : dateListString) {  //[2021-07-10,    2021-07-14,    2021-07-30,    2021-07-31]
            /*
             private String onThatDay;                      //2021-07-10  2021-07-14  2021-07-30  2021-07-31
             private List<Object> onThatDayInfo;
             private List<String> onThatDayMessage;
             */
            LifeCycleTimeLinePOJO lifeCycleTimeLinePOJO = new LifeCycleTimeLinePOJO();

            List<String> onThatDayMessage = new ArrayList<>();
            /*
             *按照顺序设置了日期数
             */
            lifeCycleTimeLinePOJO.setOnThatDay(date);

            for (Object o : objectList) {                                //封装了Resource,Interview,Try,所有的Backview信息

                if( o != null){
                    if (o.getClass().getName() == "com.feicheng.iou.entity.Resource") { //如果是Resource
                        Resource resource1 = (Resource) o;                       //强转成Resource
                        if (date.equals(resource1.getCt().toString().substring(0, 10))) { //如果在对应的那天
                            String name = studentMapper.selectById(resource1.getStudentId()).getName();
                            onThatDayMessage.add(name + "在" + resource1.getCt().toString().substring(11, 16) + "被添加了线索");
                        }
                    } else if (o.getClass().getName() == "com.feicheng.iou.entity.Interview") { //如果是Interview
                        Interview interview = (Interview) o;                   //强转成Interview
                        if (date.equals(interview.getDateTime().toString().substring(0, 10))) { //如果在对应的那天
                            String name = studentMapper.selectById(interview.getStudentId()).getName();
                            onThatDayMessage.add(name + "在" + interview.getDateTime().toString().substring(11, 16) + "到访了");
                        }

                    } else if (o.getClass().getName() == "com.feicheng.iou.entity.Try") { //如果是Try
                        Try try1 = (Try) o;
                        if (date.equals(try1.getDateTime().toString().substring(0, 10))) { //如果在对应的那天
                            String name = studentMapper.selectById(try1.getStudentId()).getName();
                            onThatDayMessage.add(name + "在" + try1.getDateTime().toString().substring(11, 16) + "试听了");
                        }

                    }
                    else if (o.getClass().getName() == "com.feicheng.iou.entity.Baoming") { //如果是Baoming
                        Baoming baoming = (Baoming) o;
                        if (date.equals(baoming.getDateTime().toString().substring(0, 10))) { //如果在对应的那天
                            String name = studentMapper.selectById(baoming.getStudentId()).getName();
                            onThatDayMessage.add(name + "在" + baoming.getDateTime().toString().substring(11, 16) + "报名了");
                        }
                    }
                    else if (o.getClass().getName() == "com.feicheng.iou.entity.Backview") { //如果是Backview
                        Backview backview = (Backview) o;
                        if (date.equals(backview.getDateTime().toString().substring(0, 10))) { //如果在对应的那天
                            //组装信息
                            if (backview.getStageId() == StatuConstant.RESOURCE_STAGE_ID) {
                                StageName = "线索阶段";
                            }
                            if (backview.getStageId() == StatuConstant.INTERVIEW_STAGE_ID) {
                                StageName = "到访阶段";
                            }
                            if (backview.getStageId() == StatuConstant.TRY_STAGE_ID) {
                                StageName = "试听阶段";
                            }
                            if(backview.getStageId() == StatuConstant.BAOMING_STAGE_ID){
                                StageName = "报名阶段";
                            }
                            String name = studentMapper.selectById(backview.getStudentId()).getName();
                            onThatDayMessage.add("针对" + name + "在" + backview.getCt().toString().substring(11, 16) + "在" + StageName + "做了回访");
                        }
                    }
                }
            }

            lifeCycleTimeLinePOJO.setOnThatDayMessage(onThatDayMessage);
            lifeCycleTimeLinePOJOList.add(lifeCycleTimeLinePOJO);
        }
        return ResultInfo.success(lifeCycleTimeLinePOJOList);
    }


    /**
     * @param resourcePublicSeaParamPOJO 学生Id
     * @return Resource
     * @Author wuweinan
     * @Description 查询公海信息
     * 声明周期方法.
     * @Date 2021-6-29 17:38
     */
    @Override
    public ResultInfo selectPublicSea(ResourcePublicSeaParamPOJO resourcePublicSeaParamPOJO) {
        log.info("ResourceServiceImpl的selectPublicSea进入");

        //查询出的list信息
        List<ResourcePublicSeaReturnListPOJO> resourcePublicSeaReturnListPOJOS =
                resourceMapper.selectPublicSea(resourcePublicSeaParamPOJO);


        //查询出的List信息的条数,totalCount
        Integer totalCount = resourceMapper.statisticsSelectPublicSea(resourcePublicSeaParamPOJO);

        //获取在第几页,page
        Integer page = resourcePublicSeaParamPOJO.getPage();

        //size
        Integer size = resourcePublicSeaParamPOJO.getSize();

        //totalPage
        Double doubleCount = (double) totalCount / size;
        double ceil = Math.ceil(doubleCount);
        int totolPage = (int) ceil;

        //封装信息
        resourcePublicSeaReturnPOJO.setPage(page);
        resourcePublicSeaReturnPOJO.setSize(size);
        resourcePublicSeaReturnPOJO.setTotalCount(totalCount);
        resourcePublicSeaReturnPOJO.setTotalPage(totolPage);
        resourcePublicSeaReturnPOJO.setList(resourcePublicSeaReturnListPOJOS);
        log.info("ResourceServiceImpl的selectPublicSea返回");
        return ResultInfo.success(resourcePublicSeaReturnPOJO);
    }


    /*
     * @Author luoxin
     * @Description //处理添加线索的业务的service实现类
     * @Date 下午12:05 2021/6/29
     * @Param  resoucePOJO 包含 Resource Student ResourceRecord
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo insert(ResourcePOJO resourcePOJO) {
        log.info("ResourceServiceImpl类insert进入,参数为: " + resourcePOJO);

        //解析POJO封装到entity
        Student student = resourcePOJO.getStudent();//解析Resource
        Resource resource = resourcePOJO.getResource();//解析Student
        ResourceRecord resourceRecord = resourcePOJO.getResourceRecord();//解析ResourceRecord
        ReservationBackview reservationBackview = new ReservationBackview();//解析ReservationBackview
        ReservationInterview reservationInterview = new ReservationInterview();//解析ReservationInterview

        //处理student添加，调用mapper
        int insertStudentResult = studentMapper.insert(student);
        //验证是否成功插入student
        if (insertStudentResult == 0) {
            throw new SystemException(ReturnCode.STUDENT_INSERT_FAIL);
        }

        //取到插入的studentID
        Integer studentId = student.getId();
        //设置resource添加时默认Statu为未分配
        resource.setStatu(StatuConstant.WEIFENPEI);
        //将取到studentID插入resource
        resource.setStudentId(studentId);
        //处理resource添加，调用mapper
        int insertResourceResult = resourceMapper.insert(resource);
        //验证是否成功插入resource
        if (insertResourceResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_INSERT_FAIL);
        }

        //取到插入的resourceID
        Integer resourceId = resource.getId();
        //将取到的resourceID插入resouceRecord
        resourceRecord.setResourceId(resourceId);
        //处理resourceRecord添加，调用mapper
        int insertResouceRecordResult = resourceRecordMapper.insert(resourceRecord);
        //验证是否成功插入resourceRecord
        if (insertResouceRecordResult == 0) {
            throw new SystemException(ReturnCode.RESOURCERECORD_INSERT_FAIL);
        }

        //取到插入线索的stageId
        reservationBackview.setStageId(1);
        //取到插入的studentID
        reservationBackview.setStudentId(student.getId());
        //处理reservationBackview添加，调用mapper
        int insertReservationBackview = reservationBackviewMapper.insert(reservationBackview);
        //验证是否成功插入resourceRecord
        if (insertReservationBackview == 0) {
            throw new SystemException(ReturnCode.INSERT_RESERVATION_BACKVIEW_FAIL);
        }

        //取到插入的studentID
        reservationInterview.setStudentId(student.getId());
        //处理reservationInterview添加，调用mapper
        int insertReservationInterview = reservationInterviewMapper.insert(reservationInterview);
        //验证是否成功插入resourceRecord
        if (insertReservationInterview == 0) {
            throw new SystemException(ReturnCode.INSERT_RESERVATION_BACKVIEW_FAIL);
        }



        log.info("ResourceServiceImpl类insert结束");
        return ResultInfo.success();
    }

    /*
     * @Author luoxin
     * @Description //处理修改线索的业务的srevice实现类
     * @Date 下午3:33 2021/6/29
     * @Param resoucePOJO 包含 Resource Student ResourceRecord ReservationBackview ReservationInterview
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo update(ResourcePOJO resourcePOJO) {
        log.info("ResourceServiceImpl类update进入,参数为: " + resourcePOJO);

        //解析POJO封装到entity
        Student student = resourcePOJO.getStudent();//解析Student
        Resource resource = resourcePOJO.getResource();//解析Resource
        ResourceRecord resourceRecord = resourcePOJO.getResourceRecord();//解析ResourceRecord
        ReservationBackview reservationBackview = resourcePOJO.getReservationBackview();//解析ReservationBackview
        ReservationInterview reservationInterview = resourcePOJO.getReservationInterview();//解析ReservationInterview

        //处理student修改，调用mapper
        int updateStudentByIdResult = studentMapper.updateById(student);
        //验证是否成功修改student信息
        if (updateStudentByIdResult == 0) {
            throw new SystemException(ReturnCode.STUDENT_UPDATE_FAIL);
        }

        //处理resource修改，调用mapper
        int updateResourceByIdResult = resourceMapper.updateById(resource);
        //验证是否成功修改resource信息
        if (updateResourceByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_UPDATE_FAIL);
        }

        //处理resourceRecord修改，调用mapper
        int updateResourceRecordByIdResult = resourceRecordMapper.updateById(resourceRecord);
        //验证是否成功修改resourceRecord信息
        if (updateResourceRecordByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCERECORD_UPDATE_FAIL);
        }

        //判断是否传入backview数据
        if (resourcePOJO.getReservationBackview().getDatetime() != null) {
            //处理reservationBackview修改，调用mapper
            int updateReservationBackviewByIdResult = reservationBackviewMapper.updateById(reservationBackview);
            //验证是否成功修改reservationBackview信息
            if (updateReservationBackviewByIdResult == 0) {
                throw new SystemException(ReturnCode.RESERVATIONBACKVIEW_UPDATE_FAIL);
            }
        }

        //判断是否传入Interview数据
        if (resourcePOJO.getReservationInterview().getDatetime() != null) {
            //处理reservationInterview修改，调用mapper
            int updateReservationInterviewByIdResult = reservationInterviewMapper.updateById(reservationInterview);
            //验证是否成功修改reservationInterview信息
            if (updateReservationInterviewByIdResult == 0) {
                throw new SystemException(ReturnCode.RESERVATIONINTERVIEW_UPDATE_FAIL);
            }
        }


        log.info("ResourceServiceImpl类update结束");
        return ResultInfo.success();
    }

    /*
     * @Author luoxin
     * @Description //处理查询线索列表的业务的service实现类
     * @Date 下午2:43 2021/6/30
     * @Param  resoucePOJO 包含  PageInfo Resource Student ResourceRecord ReservationBackview ReservationInterview
     * @return ResultInfo
     */
    @Override
    public ResultInfo listAll(ResourcePOJO resourcePOJO, HttpServletRequest request) {
        log.info("ResourceServiceImpl类listAll进入,参数为: " + resourcePOJO);

        //定义一个放返回数据的Map
        Map<String, Object> resultMap = new HashMap<>();

        //获取传入数据中的pege当前页，size每页条数得出当前页起始数据索引
        Integer pageIndex = PageUtil.getPageIndex(resourcePOJO.getPage(), resourcePOJO.getSize());
        //把数据索引封装到resourcePOJO
        resourcePOJO.setPageIndex(pageIndex);
        //检查是否拥有可分配权限，根据用户不同显示不同的数据
        LoginReturnPOJO loginReturnPOJO = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);
        List<PermissionListPOJO> permissions = loginReturnPOJO.getPermissions();

        //定一个boolean的变量校验权限是否为可分配
        boolean kefenpeiFlag = false;
        for (PermissionListPOJO permissionListPOJO : permissions) {
            List<PermissionLevelTwoPOJO> permissionsTwo = permissionListPOJO.getPermissions();
            for (PermissionLevelTwoPOJO permissionLevelTwoPOJO : permissionsTwo) {
                if (permissionLevelTwoPOJO.getName().equals("可分配")) {
                    kefenpeiFlag = true;
                    break;  //如何退出两层for需调研
                }
            }
        }

        if (resourcePOJO.getResource().getAutor() == null) {
            if (kefenpeiFlag) {
                resourcePOJO.getResource().setAutor(null);
            } else {
                resourcePOJO.getResource().setAutor(loginReturnPOJO.getUser().getUserId());
            }
        }
        //调用Mapper中查询条数的方法得出条数封装进resourcePOJO
        resourcePOJO.setTotal(resourceMapper.queryResourceAllCount(resourcePOJO));
        //根据传入的pojo查询，结果封装到resourcePOJOSList
        List<ResultResourcePOJO> resultResourcePOJOSList = resourceMapper.queryResourceAll(resourcePOJO);
        //获取pageutil里的pageinfo里的数据封装到pageinfo这个map
        Map<String, Integer> pageInfo = PageUtil.getPageInfo(resourcePOJO.getPage(), resourcePOJO.getSize(), resourcePOJO.getTotal());

        //把pageinnfo这个map封装到resultMap中
        resultMap.put("pageInfo", pageInfo);
        //把resourcePOJOSList这个list封装到resultMap中
        resultMap.put("list", resultResourcePOJOSList);
        //把resultMap封装到ResultInfo中
        ResultInfo resultInfo = ResultInfo.success(resultMap);

        /*
        封装进session
         */
        List<ResultResourcePOJO> resultResourcePOJOS = resourceMapper.excelQueryResourceAll(resourcePOJO);

        List<ExcelOutModel> excelModels = excelService.parseResultResourcePOJO(resultResourcePOJOS);
        //excelmodels值的准确性
        HttpSession session = request.getSession();
        session.setAttribute("excelModels", excelModels);

        String id = session.getId();
        String[] valueNames = session.getValueNames();


        log.info("ResourceServiceImpl类listAll结束");
        return resultInfo;
    }


    /*
     * @Author luoxin
     * @Description //处理查询单个线索的业务的service实现类
     * @Date 下午3:28 2021/7/13
     * @Param resoucePOJO 包含  PageInfo Resource Student ResourceRecord ReservationBackview ReservationInterview
     * @return ResultInfo
     */
    @Override
    public ResultInfo selectinfo(Integer id) {
        log.info("ResourceServiceImpl类selectinfo进入,参数为: " + id);

        //定义一个放返回数据的Map
        Map<String, Object> resultMap = new HashMap<>();
        //定义一个存放studentID的map
        HashMap<String, Object> studentIdMap = new HashMap<String, Object>();
        //定义一个存放resourceID的map
        HashMap<String, Object> resourceIdMap = new HashMap<String, Object>();

        //根据resourceID查找，取到studentID
        Integer studentId = resourceMapper.selectById(id).getStudentId();
        //把查到的学生ID封装到studentIdMap中
        studentIdMap.put("student_Id", studentId);
        //把resourceID封装到resourceIdMap中
        resourceIdMap.put("resource_Id", id);

        //将所有查询到的信息封装到返回信息的map中
        resultMap.put("resource", resourceMapper.selectById(id));
        resultMap.put("student", studentMapper.selectById(studentId));
        resultMap.put("resourceRecord", resourceRecordMapper.selectByMap(resourceIdMap).get(0));

        //判断查询结果是不是为空，如果为空map中reservationInterview赋值null，不为空将信息封装到map中
        if (reservationInterviewMapper.selectByMap(studentIdMap).size() != 0) {
            resultMap.put("reservationInterview", reservationInterviewMapper.selectByMap(studentIdMap).get(0));
        } else {
            resultMap.put("reservationInterview", new ReservationInterview());
        }

        //判断查询结果是不是为空，如果为空map中reservationBackview赋值null，不为空将信息封装到map中
        if (reservationBackviewMapper.selectByMap(studentIdMap).size() == 0) {
            resultMap.put("reservationBackview", new ReservationBackview());
        } else {
            resultMap.put("reservationBackview", reservationBackviewMapper.selectByMap(studentIdMap).get(0));
        }
//        if reservationInterviewMapper.selectByMap(studentIdMap).get(0)
//        if reservationBackviewMapper.selectByMap(studentIdMap).get(0)
//        resultMap.put("reservationInterview", reservationInterviewMapper.selectByMap(studentIdMap).get(0));
//        resultMap.put("reservationBackview", reservationBackviewMapper.selectByMap(studentIdMap).get(0));
        //把resultMap封装到ResultInfo中
        ResultInfo resultInfo = ResultInfo.success(resultMap);

        log.info("ResourceServiceImpl类selectinfo结束");
        return resultInfo;
    }

    /*
     * @Author luoxin
     * @Description //处理删除线索的业务的service实现类
     * @Date 下午3:34 2021/7/13
     * @Param resoucePOJO 包含  PageInfo Resource Student ResourceRecord ReservationBackview ReservationInterview
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo delete(ResourcePOJO resourcePOJO) {
        log.info("ResourceServiceImpl类selectinfo进入,参数为: " + resourcePOJO);
        log.info("resourcePOJO.getReservationBackview()." + resourcePOJO.getReservationBackview());
        //解析POJO封装到entity
        Integer studentId = resourcePOJO.getStudent().getId();//解析Student中ID
        Integer resourceId = resourcePOJO.getResource().getId();//解析Resource中ID
        Integer resourceRecordId = resourcePOJO.getResourceRecord().getId();//解析ResourceRecord中ID
        ReservationBackview reservationBackview = resourcePOJO.getReservationBackview();//解析reservationBackview
        ReservationInterview reservationInterview = resourcePOJO.getReservationInterview();//解析reservationInterview


        //处理student删除，调用mapper
        int deleteStudentbyIdResult = studentMapper.deleteById(studentId);
        //验证是否成功删除student信息
        if (deleteStudentbyIdResult == 0) {
            throw new SystemException(ReturnCode.STUDENT_DELETE_FAIL);
        }
        //处理resource删除，调用mapper
        int deleteResourceByIdResult = resourceMapper.deleteById(resourceId);
        //验证是否成功删除resource信息
        if (deleteResourceByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_DELETE_FAIL);
        }

        //处理resourceRecord删除，调用mapper
        int deleteResourceRecordByIdResult = resourceRecordMapper.deleteById(resourceRecordId);
        //验证是否成功删除resourceRecord信息
        if (deleteResourceRecordByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCERECORD_DELETE_FAIL);
        }

        if (reservationInterview != null) {
            Integer reservationInterviewId = reservationInterview.getId();//解析reservationInterviewId中ID
            //处理reservationInterview删除，调用mapper
            int deleteReservationInterviewByIdResult = reservationInterviewMapper.deleteById(reservationInterviewId);
            //验证是否成功删除reservationInterview信息
            if (deleteResourceRecordByIdResult == 0) {
                throw new SystemException(ReturnCode.RESERVATIONINTERVIEW_DELETE_FAIL);
            }
        }

        if (reservationBackview != null) {
            Integer reservationBackviewId = reservationBackview.getId();//解析reservationBackviewId中ID
            //处理reservationBackview删除，调用mapper
            int deleteReservationBackviewByIdResult = reservationBackviewMapper.deleteById(reservationBackviewId);
            //验证是否成功删除reservationBackview信息
            if (deleteResourceRecordByIdResult == 0) {
                throw new SystemException(ReturnCode.RESERVATIONBACKVIEW_DELETEE_FAIL);
            }
        }

        log.info("ResourceServiceImpl类delete结束");
        return ResultInfo.success();
    }

    /*
     * @Author luoxin
     * @Description //处理分配线索的业务的service实现类
     * @Date 下午3:35 2021/7/13
     * @Param resoucePOJO 包含  Resource ResourceRecord User
     * @return ResultInfo
     */

    @Transactional
    @Override
    public ResultInfo updateAutor(ResourcePOJO resourcePOJO) {
        log.info("ResourceServiceImpl类updateAutor进入,参数为: " + resourcePOJO);

        //解析POJO封装到entity
        Resource resource = resourcePOJO.getResource();//解析Resource
        ResourceRecord resourceRecord = resourcePOJO.getResourceRecord();//解析ResourceRecord
        Integer userId = resourcePOJO.getUser().getUserId();//解析User中ID

        //修改resource的Statu为线索待回访
        resource.setStatu(StatuConstant.XIANSUODAIHUIFANG);
        //处理resource修改，调用mapper
        resource.setAutor(userId);
        int updateResourceByIdResult = resourceMapper.updateById(resource);
        //验证是否成功修改resource信息
        if (updateResourceByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_UPDATE_FAIL);
        }

        //处理resourceRecord修改，调用mapper
        resourceRecord.setAutor(userId);
        int updateResourceRecordByIdResult = resourceRecordMapper.updateById(resourceRecord);
        //验证是否成功修改resourceRecord信息
        if (updateResourceRecordByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCERECORD_UPDATE_FAIL);
        }

        log.info("ResourceServiceImpl类updateAutor结束");
        return ResultInfo.success();

    }

    /*
     * @Author luoxin
     * @Description TODO
     * @Date 11:53 上午 2021/7/26
     * @param ResourcePOJO
     * @return ResultInfo
     */
    @Override
    public ResultInfo abandonResource(ResourcePOJO resourcePOJO) {
        log.info("ResourceServiceImpl类abandon进入");

        //解析POJO封装到entity
        Resource resource = resourcePOJO.getResource();//解析Resource

        //处理resource修改，调用mapper（修改为已放弃）
        resource.setStatu(StatuConstant.YIFANGQI);
        //验证是否成功修改resource信息
        int abandonResourceResult = resourceMapper.updateById(resource);
        if (abandonResourceResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_UPDATE_FAIL);
        }

        log.info("ResourceServiceImpl类abandon结束");
        return ResultInfo.success();
    }

}
